//
//  AddressViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/10/24.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SwiftyJSON
import SVProgressHUD

protocol AddressViewControllerDelegate {
    func giveTheAddressToProcessOrderVC(_ dataArr:AddressModel)
}

class AddressViewController: UIViewController,UpdataAddressViewControllerDelegate,UITableViewDelegate,UITableViewDataSource {

    var delegate : AddressViewControllerDelegate?
    
    var myTableView = UITableView(frame: CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.9-64), style: .plain)
    let ADDRESSCELL = "addressTableViewCell"
    
    var dataArr = NSMutableArray()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.creatNavView()
        self.getAddressData()
        self.creatTabel()
        self.creatAddView()
       
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    


}

extension AddressViewController{
    fileprivate func creatNavView(){
        self.view.backgroundColor = UIColor.white
        self.automaticallyAdjustsScrollViewInsets = false
        
        self.title = "ADDRESS LIST"
        
        let leftBtn = UIButton(type: .custom)
        leftBtn.setImage(UIImage(named: "nav_back"), for: UIControlState())
        leftBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        let item = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = item
        
        
        let rightItemCustomeView   = UIButton(type: UIButtonType.custom)
        rightItemCustomeView.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        rightItemCustomeView.setImage(UIImage(named:"nav_close"), for: UIControlState())
        rightItemCustomeView.addTarget(self, action: #selector(rightBtnClick), for: UIControlEvents.touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItemCustomeView);
        
        
    }
    
    func leftBtnClick(){
        self.navigationController?.popViewController(animated: true)
    }
    
    func rightBtnClick(){
        self.navigationController?.popToRootViewController(animated: true)
    }

}

extension AddressViewController{
    fileprivate func getAddressData(){
        let parmas = ["main_page":"address_book","zenid":UserSession.shareInstance.cookie!]
        NetworkTool.shareInstance.request(.get, urlString: APIBASE, parmas: parmas as [String : NSObject]) { (result, error) in
            if result != nil{
//                let json = JSON(result!)
//                print(json)
                
                let arr = (result as! NSDictionary)["data"] as? [[String:NSObject]]
                for dic in arr!{
                    let model = AddressModel(dictionary: dic as NSDictionary)
                    self.dataArr.add(model)
                }
                self.myTableView.reloadData()
                
            }else{
                SVProgressHUD.showError(withStatus: "get cart data error:" + String(describing: error))
                print("get cart data error:" + String(describing: error))
            }
        }
        
        
    }
}

extension AddressViewController{
    fileprivate func creatTabel(){
        myTableView.delegate = self
        myTableView.dataSource = self
        self.view.addSubview(myTableView)
        let nib = UINib(nibName: "AddressTableViewCell", bundle: nil)
        myTableView.register(nib, forCellReuseIdentifier: ADDRESSCELL)
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ADDRESSCELL)
        cell?.selectionStyle = .none
        let model = self.dataArr[indexPath.row] as? AddressModel
        (cell as? AddressTableViewCell)?.model = model
        
        
        return cell!
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SCREEN_HEIGHT*0.2
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.delegate?.giveTheAddressToProcessOrderVC(self.dataArr[indexPath.row] as! AddressModel)
        self.navigationController?.popViewController(animated: true)
    }
    
    
//    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
//        let deleteRowAction = UITableViewRowAction(style: .destructive, title: "DELETE", handler: (UITableViewRowAction, IndexPath){
//            
//        })
//    }
    
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        
        let model = self.dataArr[indexPath.row] as! AddressModel
        let urlStr = APIBASE + "main_page=address_book_process"
        
        let parma = ["act":"delete","address_book_id":model.address_book_id!]
        
        NetworkTool.shareInstance.request(.post, urlString: urlStr, parmas: parma as [String : NSObject], finishedBlock: { (result, error) in
            let status = String(describing: (result as! NSDictionary)["status"]!)
            if status == "1"{
                SVProgressHUD.showSuccess(withStatus: "Delete the success！")
                
                self.dataArr.removeAllObjects()
                self.getAddressData()
                
            }else{
                SVProgressHUD.showInfo(withStatus: String(describing: (result as! NSDictionary)["status_message"]))
            }
            
        })
        
        
        
    }
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "DELETE"
    }
    
}

extension AddressViewController{
    fileprivate func creatAddView(){
        let addView = UIView()
        addView.frame = CGRect(x: 0, y: SCREEN_HEIGHT*0.9, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.1)
        addView.backgroundColor = UIColor.white
        self.view.addSubview(addView)
        
        let addBtn  = UIButton(type: .custom)
        addBtn.frame = CGRect(x: SCREEN_WIDTH*0.05, y: SCREEN_HEIGHT*0.01, width: SCREEN_WIDTH*0.9, height: SCREEN_HEIGHT*0.08)
        addBtn.setTitle("Add shipping address", for: UIControlState())
        addBtn.setTitleColor(UIColor.white, for: UIControlState())
        addBtn.backgroundColor = UIColor.black
        addBtn.addTarget(self, action: #selector(addBtnClick), for: .touchUpInside)
        addView.addSubview(addBtn)
        
        
    }
    
    
    func addBtnClick(){
        let updateVC = UpdataAddressViewController()
        updateVC.delegate = self
        
        self.navigationController?.pushViewController(updateVC, animated: true)
        
    }
    
    func giveTheAddressToAddressVC() {
        self.dataArr.removeAllObjects()
        self.getAddressData()
    }
}























